package com.itheima.appserver.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.excepiton.BusinessException;
import com.itheima.appserver.excepiton.ErrorResult;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.commons.pojo.domain.*;
import com.itheima.commons.vo.reception.*;
import com.itheima.dubbo.interfaces.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 问卷列表
 */
@Service
public class QuestionNaireService {
    @Reference
    QuestionNaireApi questionNaireApi;
    @Reference
    SoulQuestionApi soulQuestionApi;
    @Reference
    SoulQuestionOptionApi soulQuestionOptionApi;
    @Reference
    QuestionUserLockApi questionUserLockApi;
    @Reference
    QuestionNaireResultApi questionNaireResultApi;
    @Reference
    QuestionNaireReportApi questionNaireReportApi;
    @Reference
    UserInfoApi userInfoApi;

    /**
     * 问卷列表
     *
     * @return
     */
    public List<QuestionNaireVo> getResultList() {

        List<QuestionNaireVo> questionNaireVoList = new ArrayList<>();
        //通过当前用户id查询lock表是否有数据
        List<QuestionUserLock> userLocks = questionUserLockApi.findById(UserThreadLocal.getUserId());
        //如果没有 创建默认数据
        String reportId = null;
        if (CollUtil.isEmpty(userLocks)) {
            //获取所有问卷数据,将问卷赋值给默认数据
            List<Questionnaire> questionnaireList = questionNaireApi.findAllNai();
            for (Questionnaire questionnaire : questionnaireList) {
                QuestionUserLock questionUserLock = new QuestionUserLock();
                questionUserLock.setUserId(UserThreadLocal.getUserId());
                questionUserLock.setQuestionnaireId(questionnaire.getId());
                //如果是初级就设为开放
                if (questionnaire.getId().equals(Long.valueOf(1))) {
                    questionUserLock.setIsLock(0);
                } else {
                    questionUserLock.setIsLock(1);
                }
                questionUserLock.setCreated(new Date());
                questionUserLock.setUpdated(new Date());
                //将默认数据添加到数据库
                questionUserLockApi.add(questionUserLock);
            }
        }
        //再通过当前用户id查询一遍userlock表
        List<QuestionUserLock> userLocksTwo = questionUserLockApi.findById(UserThreadLocal.getUserId());

        //通过userlock表中的问卷id取查询对应的问卷表
        List<Questionnaire> questionnaireList = new ArrayList<>();
        for (QuestionUserLock questionUserLock : userLocksTwo) {
            questionnaireList.add(questionNaireApi.findAllById(questionUserLock.getQuestionnaireId()));
        }
        for (Questionnaire questionnaire : questionnaireList) {
            //创建要返回的vo对象
            QuestionNaireVo questionNaireVo = new QuestionNaireVo();
            questionNaireVo.setId(questionnaire.getId().toString());
            questionNaireVo.setName(questionnaire.getName());
            questionNaireVo.setCover(questionnaire.getCover());
            questionNaireVo.setLevel(questionnaire.getLevel().toString());
            questionNaireVo.setReportld(reportId);
            questionNaireVo.setStar(questionnaire.getStar());

            //获取所有的问题
            List<SoulQuestion> allQuestion = soulQuestionApi.findAllById(Convert.toLong(questionNaireVo.getId()));
            //遍历所有的问题给问题对象赋值
            //创建问题集合
            List<QuestionsVo> questionList = new ArrayList<>();
            for (SoulQuestion soulQuestion : allQuestion) {
                //创建问题对象
                QuestionsVo questionsVo = new QuestionsVo();
                questionsVo.setId(soulQuestion.getId().toString());
                questionsVo.setQuestion(soulQuestion.getStem());
                questionList.add(questionsVo);

                //option还没有赋值
            }
            questionNaireVo.setQuestions(questionList);
            for (QuestionsVo questionsVo : questionList) {
                List<OptionsVo> optionsVos = new ArrayList<>();
                //通过问题id找出所有的选项
                //通股票问题id查询出所有的选项
                List<SoulQuestionOption> options = soulQuestionOptionApi.findAllOptionByQuestionId(Convert.toLong(questionsVo.getId()));
                for (SoulQuestionOption option1 : options) {
                    OptionsVo optionsVo = new OptionsVo();
                    optionsVo.setId(option1.getId().toString());
                    optionsVo.setOption(option1.getContent());
                    optionsVos.add(optionsVo);
                }
                questionsVo.setOptions(optionsVos);
            }
            questionNaireVoList.add(questionNaireVo);
        }

        List<Long> isLock = CollUtil.getFieldValues(userLocksTwo, "isLock", Long.class);
        //遍历 返回的vo集合  和添加过数据后的 锁表 将锁状态添加到vo集合中的属性中
        Integer count = 0;
        for (QuestionNaireVo questionNaireVo : questionNaireVoList) {
            questionNaireVo.setIsLock(Convert.toInt(isLock.get(count)));
            count++;
        }
//        此时还剩下最新报告和 问题集合没有赋值
//        获取此用户的所有报告信息
        List<QuestionnaireReport> reportList = questionNaireReportApi.findAllReportByUserId(UserThreadLocal.getUserId());
        //排除null
        //如果为null 0 1 1  如果为1 ，0 0 1 如果为2 ，0 0 0
        //遍历返回volist集合 进行赋值
        for (QuestionNaireVo questionNaireVo : questionNaireVoList) {
            for (QuestionnaireReport report : reportList) {
                if (reportList.isEmpty()) {
                } else if (reportList.size() == 1 && questionNaireVo.getId().equals(2)) {
                    questionNaireVo.setReportld(report.getId().toString());
                    questionNaireVo.setIsLock(0);
                } else if (reportList.size() == 2 && questionNaireVo.getId().equals(3)) {
                    questionNaireVo.setReportld(report.getId().toString());
                    questionNaireVo.setIsLock(0);
                }
            }
        }

        //给问题集合赋值
        //查找所有和问卷id对应的试题
        return questionNaireVoList;
    }


    /**
     * 查看结果
     *
     * @param id
     * @return
     */
    public QuestionReportVo getResult(String id) {
        QuestionReportVo questionReportVo = new QuestionReportVo();
        QuestionnaireReport report = questionNaireReportApi.findAllReportById(id);
        questionReportVo.setConclusion(report.getConclusion());
        questionReportVo.setCover(report.getCover());

        List<Dimension> dimensionList = new ArrayList<>();
        dimensionList.add(new Dimension("外向", report.getExtroversion() + "%"));
        dimensionList.add(new Dimension("判断", report.getJudgement() + "%"));
        dimensionList.add(new Dimension("抽象", report.getAbstraction() + "%"));
        dimensionList.add(new Dimension("理性", report.getRetionality() + "%"));
        questionReportVo.setDimensions(dimensionList);

        List<SimilarYou> similarYouList = new ArrayList<>();
        // 返回10条相识的人
        List<QuestionnaireReport> questionnaireReportList = questionNaireReportApi.querySimilarYou(report.getUserId(), report.getConclusion());
        if (CollUtil.isNotEmpty(questionnaireReportList)) {
            List<Long> userIds = CollUtil.getFieldValues(questionnaireReportList, "userId", Long.class);
            Map<Long, UserInfo> userInfoMap = userInfoApi.findUserInfoByUserIds(userIds);
            for (UserInfo userInfo : userInfoMap.values()) {
                similarYouList.add(new SimilarYou(Convert.toInt(userInfo.getUserId()), userInfo.getLogo()));
            }
        }
        questionReportVo.setSimilarYou(similarYouList);

        return questionReportVo;
    }

    /**
     * 提交问卷
     *
     * @param answers1
     * @return
     */
    public String testSoul(List<Answers> answers1) {
        Long questionId = 0L;
        Integer scope = 0;
        for (Answers answers : answers1) {
            questionId = Convert.toLong(answers.getQuestionId());
            Long optionId = Convert.toLong(answers.getOptionId());
            //问题id和选项id都相等
            SoulQuestionOption option = soulQuestionOptionApi.findOneByQueIdAndOpt(questionId, optionId);
            scope += option.getScore();
        }
        //通过问题id查询到问卷id
        SoulQuestion soulQuestion = soulQuestionApi.findOneByQueId(questionId);
        Long questionnaireId = soulQuestion.getQuestionnaireId();
        //通过问卷id去查询result表
        List<QuestionnaireResult> results = questionNaireResultApi.findByNaiId(questionnaireId);
        //创建报告对象
        for (QuestionnaireResult result : results) {
            String[] split = result.getScope().split(",");
            if (scope >= Integer.valueOf(split[0]) && scope <= Integer.valueOf(split[1])) {
                QuestionnaireReport questionnaireReport = new QuestionnaireReport();
                questionnaireReport.setUserId(UserThreadLocal.getUserId());
                Integer[] integers = {60, 70, 80, 90};
                questionnaireReport.setExtroversion(RandomUtil.randomEle(integers));
                questionnaireReport.setJudgement(RandomUtil.randomEle(integers));
                questionnaireReport.setAbstraction(RandomUtil.randomEle(integers));
                questionnaireReport.setRetionality(RandomUtil.randomEle(integers));

                questionnaireReport.setCreated(new Date());
                questionnaireReport.setUpdated(new Date());
                questionnaireReport.setConclusion(result.getContent());
                questionnaireReport.setCover(result.getCover());
                questionNaireReportApi.add(questionnaireReport);
            }
        }

        List<QuestionnaireReport> allReport = questionNaireReportApi.findAllReport(UserThreadLocal.getUserId());
        List<QuestionUserLock> lockList = questionUserLockApi.findById(UserThreadLocal.getUserId());
        switch (allReport.size()) {
            case 1:
                lockList.get(1).setIsLock(0);
                questionUserLockApi.update(lockList.get(1));
                break;
            case 2:
                lockList.get(2).setIsLock(0);
                questionUserLockApi.update(lockList.get(2));
                break;
            default:
                throw new BusinessException(ErrorResult.soulTestError());
        }
        // 该用户当前的报告
        QuestionnaireReport currentReport = questionNaireReportApi.queryCurrentReport(UserThreadLocal.getUserId());
        return currentReport.getId().toString();
    }
}

